package data_access;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;

import modelo.FormularioSolicitudEstudio;
import modelo.Sintoma;

public class FormulariosManager
{
	public static FormularioSolicitudEstudio getById(int id)
	{
		Connection c = ConnectionFactory.getConnection();
		try
		{
			PreparedStatement ps = c
					.prepareStatement("SELECT fecha, nroMuestra, idPaciente, estaPendiente FROM FormulariosSolicitudEstudio WHERE nro = ?");
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();

			FormularioSolicitudEstudio fse = null;
			if (rs.next())
			{
				fse = new FormularioSolicitudEstudio();

				fse.setNro(id);
				
				Date fecha = rs.getDate(1);
				fse.setFecha(fecha);

				String nroMuestra = rs.getString(2);
				fse.setnroMuestra(nroMuestra);

				int idPaciente = rs.getInt(3);
				fse.setPaciente(PacientesManager.getPacienteById(idPaciente));

				boolean estaPendiente = rs.getBoolean(4);
				fse.setPendiente(estaPendiente);

				fse.addSintomas(getSintomasByFormulario(fse, c));
			}
			return fse;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			ConnectionFactory.closeConnection(c);
		}

		return null;
	}

	private static Collection<Sintoma> getSintomasByFormulario(
			FormularioSolicitudEstudio fse, Connection c)
	{
		Collection<Sintoma> sintomas = new ArrayList<Sintoma>();
		try
		{
			PreparedStatement ps = c
					.prepareStatement("SELECT idSintoma FROM Sintomas_FormulariosSolicitudEstudio WHERE idFormulario = ?");
			ps.setInt(1, fse.getNro());
			ResultSet rs = ps.executeQuery();

			while (rs.next())
			{
				int idSintoma = rs.getInt(1);
				Sintoma s = SintomasManager.getById(idSintoma);
				sintomas.add(s);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return sintomas;
	}

	public static void UpdateEstado(FormularioSolicitudEstudio formulario)
	{
		Connection c = ConnectionFactory.getConnection();
		try
		{
			PreparedStatement ps = c
					.prepareStatement("UPDATE FormulariosSolicitudEstudio SET estaPendiente = 0 WHERE nro = ?");
			ps.setInt(1, formulario.getNro());
			ps.executeUpdate();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			ConnectionFactory.closeConnection(c);
		}
	}
}
